package com.nz.net.hays.www;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

//import com.example.listviewdemo.R;



//import com.nz.net.hays.www.SignUp.loginAccess;

import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;




public class Search extends ListActivity implements OnClickListener{
	private EditText jobResult;
	private Button search;
	private EditText keyword, jobClassification, salaryStart, salaryEnd;
	private String classification,location;
	private Spinner spin_classification,spin_location;
	private ProgressDialog pDialog;
	private static final String TAG_SUCCESS = "success"; 
	private static final String TAG_JOBDESCRIPTION = "jobdescription";
	private static final String TAG_DESCRIPTION = "description";
	private static final String TAG_JOBID="jobid";
	static ArrayList<HashMap<String, String>> jobdescriptionList;
	private ListView listView ;
	JSONArray jobdescription=null;
	
	JSONObject description=null; 
	//private static final Object TAG_DES="des";
	int flag=0;
	//private ArrayList() arr=new ArrayList();
	Intent i;
	JSONParser jsonParser = new JSONParser();
	//private static String url = "http://10.0.2.2/rdias/register.php";
	private static String url = "http://hays.byethost6.com/haysjobsearch.php";
	//private static String url2 = "http://hays.byethost6.com/haysgetkeywordid.php";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		//StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
		//.detectDiskReads().detectDiskWrites().detectNetwork()
		//.penaltyLog().build());
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search);
		//setContentView(R.layout.final_jobsearch_result);
		
		jobdescriptionList=new ArrayList<HashMap<String,String>>();
		
		//ListView lv=getListView();
		
		//listView = (ListView) findViewById(R.id.list);
//		ListView lv = getListView();
//		
//		lv.setOnItemClickListener(new OnItemClickListener() {
//			 
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view,
//                    int position, long id) {
//                // getting values from selected ListItem
//                String pid = ((TextView) view.findViewById(R.id.pid)).getText()
//                        .toString();
// 
//                // Starting new intent
//                //Intent in = new Intent(getApplicationContext(),
//                  //      EditProductActivity.class);
//                // sending pid to next activity
//                //in.putExtra(TAG_PID, pid);
// 
//                // starting new activity and expecting some response back
//                //startActivityForResult(in, 100);
//            }
//        });
	
	//Go To Login.java	
//		login=(Button)findViewById(R.id.login);	
//        login.setOnClickListener(new View.OnClickListener() 
//        {		
//			@Override
//			public void onClick(View view) {
//				Intent i = new Intent(getApplicationContext(), MainActivity.class);
//				startActivity(i);
//				
//			}
//		}); 
    // Close Login.java
        
     //Get all data and log in 
    	search=(Button)findViewById(R.id.imageButtonsearch);
		keyword=(EditText)findViewById(R.id.editTextKeyword);
		//jobClassification=(EditText)findViewById(R.id.editTexttest1);
		//location=(EditText)findViewById(R.id.editTexttest2);
		salaryStart=(EditText)findViewById(R.id.editTextminsalary);
		salaryEnd=(EditText)findViewById(R.id.editTextmaxsalary);
		spin_classification=(Spinner)findViewById(R.id.spinnerclassification);
		spin_location=(Spinner)findViewById(R.id.spinnerlocation);
    	//username=(EditText)findViewById(R.id.edit);
    	//password=(EditText)findViewById(R.id.password);
    	//hint=(EditText)findViewById(R.id.hint);
    	//emailid=(EditText)findViewById(R.id.email_id);
		//loginAccess obj=new loginAccess();
		//obj.execute();
	//}
		//new loginAccess().execute();
    	search.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(keyword.getText().toString().equals("")||keyword.getText().toString().equals(null)||salaryEnd.getText().toString().equals("")||salaryStart.getText().toString().equals(""))
				{					
					Toast.makeText(Search.this,"Please fill all the fields", Toast.LENGTH_LONG).show();
					return;	
				}    				//check connectivity		
				 if(!isOnline(Search.this))
				{					
					Toast.makeText(Search.this,"No network connection", Toast.LENGTH_LONG).show();
					return;	
				}
				new loginAccess().execute();
			}
			//code to check online details
			private boolean isOnline(Context mContext) {
			ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo netInfo = cm.getActiveNetworkInfo();
			if (netInfo != null && netInfo.isConnectedOrConnecting())
		   	  {
				return true;
	     		}
			    return false;
	       	}
		});
	}
//        SignUp.setOnClickListener(new View.OnClickListener() 
//        {			
//			@Override
//			public void onClick(View view) {
//				
//		
//		//check connectivity		
//				 if(!isOnline(SignUp.this))
//				{					
//					Toast.makeText(SignUp.this,"No network connection", Toast.LENGTH_LONG).show();
//					return;	
//				}
//		
//		//from login.java		
//					new loginAccess().execute();
//			}
   
		//code to check online details
//		private boolean isOnline(Context mContext) {
//		ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
//		NetworkInfo netInfo = cm.getActiveNetworkInfo();
//		if (netInfo != null && netInfo.isConnectedOrConnecting())
//	   	  {
//			return true;
//     		}
//		    return false;
//       	}
//      //Close code that check online details		
//	  }
//}
//}       //Close log in 
    
	// Response from Edit Product Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received
            // means user edited/deleted product
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }
 
    }

class loginAccess extends AsyncTask<String, String, String> {

	private	String keyW, jClassification, loc, sStart, sEnd;
	private String finalDescription;
	private JSONObject recs;
	private ArrayList<String> list;
	
	HashMap<String, String> map;
	protected void onPreExecute() {
		super.onPreExecute();
		pDialog = new ProgressDialog(Search.this);
		pDialog.setMessage("Loading...");
		pDialog.setIndeterminate(false);
		pDialog.setCancelable(true);
		pDialog.show();
	}
	@Override
	protected String doInBackground(String... arg0) {
		
		//List<NameValuePair> params2 = new ArrayList<NameValuePair>();
		//keyW=keyword.getText().toString();
		
		//params2.add(new BasicNameValuePair("keyword",keyW));
		//JSONObject json2=jsonParser.makeHttpRequest(url2, "POST", params2);
		
		//try
		//{
			//int newkeyW = json2.getInt(TAG_KEYWORDID);
		//}catch(Exception e){}	
		//keyW = json2.getString(TAG_KEYWORDID);
		
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		
		
		
		keyW=keyword.getText().toString();
		//jClassification=jobClassification.getText().toString();
		//loc=location.getText().toString();
		classification=spin_classification.getSelectedItem().toString();
		location=spin_location.getSelectedItem().toString();
		sStart=salaryStart.getText().toString();
		sEnd=salaryEnd.getText().toString();
		 //user=username.getText().toString();
		 //pwd=password.getText().toString();
		//String h=hint.getText().toString();
		//String id=emailid.getText().toString();
		
		if(!((keyW.isEmpty()||classification.isEmpty()||location.isEmpty()||sStart.isEmpty()||sEnd.isEmpty())||(keyW.equals(null)||classification.equals(null)||location.equals(null)||sStart.equals(null)||sEnd.equals(null))))
		{
			params.add(new BasicNameValuePair("keyword",keyW));
			params.add(new BasicNameValuePair("jobClassification", classification));
			params.add(new BasicNameValuePair("location", location));
			params.add(new BasicNameValuePair("salaryStart", sStart));
			params.add(new BasicNameValuePair("salaryEnd", sEnd));
			
			JSONObject json = jsonParser.makeHttpRequest(url,"POST", params);
			
			Log.d("Create Response", json.toString());
			
			try {
				int success = json.getInt(TAG_SUCCESS);
				
				if (success == 1) 
				 {
					jobdescription=json.getJSONArray(TAG_JOBDESCRIPTION);
					for(int i=0;i<jobdescription.length();i++){
						JSONObject c=jobdescription.getJSONObject(i);
						
						String jobid=c.getString(TAG_JOBID);
						String jobdes=c.getString(TAG_DESCRIPTION);
						map = new HashMap<String, String>();
						map.put(TAG_JOBID, jobid);
						map.put(TAG_DESCRIPTION, jobdes);
						
						jobdescriptionList.add(map);
					}
					
					//publishProgress("");
				  flag=0;	
				  //i.putExtra("username",user);
				 
				
				 }
				 else
				 {
					// failed to Sign in
					flag=1;
				}
			}catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(Search.this,e.getMessage(), Toast.LENGTH_LONG).show(); 
			//catch (JSONException e) {
				//e.printStackTrace();
			}
			
		}
		
		else
		{	
			Toast.makeText(getApplicationContext(), "All Fields are required.", Toast.LENGTH_LONG).show();
			//return;
		}
		return null;
				
	}
	protected void onPostExecute(String file_url) {
		pDialog.dismiss();
		try {
			if(flag==0)
			{
				i=new Intent(getApplicationContext(),AllProductsActivity.class);
				startActivity(i);
//				runOnUiThread(new Runnable() {
//					public void run() {
//						/**
//	                     * Updating parsed JSON data into ListView
//	                     * */
//						//setContentView(R.layout.final_jobsearch_result);
//						ListView lv=getListView();
//	                    ListAdapter adapter = new SimpleAdapter(
//	                            Search.this, jobdescriptionList,
//	                            R.id.list_item, new String[] { TAG_JOBID,
//	                                    TAG_DESCRIPTION},
//	                            new int[] { R.id.pid, R.id.name });
//	                    // updating listview
//	                    
//	                    setListAdapter(adapter);
//					}
//				});
			}
				
				 //Intent i = new Intent(SignUp.this,Update.class);				
//				i = new Intent(getApplicationContext(),FinalJobSearchResult.class);
////				 //i.putExtra("jobResult",finalDescription);
//			ArrayList values= new ArrayList(map.values());   
//			for(Object value:values){
//				i.putExtra("jobResult", value.toString());
//				startActivity(i);
//			}
				//i.putStringArrayListExtra("jobResult", jobdescriptionList);
//				//i.putExtra("jobResult", list);
//				 
//				  //i.putExtra("password",pwd);
				  
//				  finish();
//			}
			if(flag==1)
			{
				Toast.makeText(Search.this,"No Results Found For Search Criteria.", Toast.LENGTH_LONG).show();
				
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
	}

	
  }

@Override
public void onClick(View v) {
	// TODO Auto-generated method stub
	
}
}
	
